package simonby.top.annualring.application.service;

import cn.dev33.satoken.stp.StpUtil;
import simonby.top.annualring.domain.model.User;
import simonby.top.annualring.domain.model.FamilyTree;
import simonby.top.annualring.domain.model.UserFamily;
import simonby.top.annualring.domain.repository.UserRepository;
import simonby.top.annualring.domain.repository.FamilyTreeRepository;
import simonby.top.annualring.domain.repository.UserFamilyRepository;
import simonby.top.annualring.infrastructure.repository.UserRepositoryImpl;
import simonby.top.annualring.infrastructure.repository.FamilyTreeRepositoryImpl;
import simonby.top.annualring.infrastructure.repository.UserFamilyRepositoryImpl;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 权限应用服务
 * 处理系统权限相关的业务逻辑
 */
@Service
public class PermissionApplicationService {
    
    private final UserRepository userRepository;
    private final FamilyTreeRepository familyTreeRepository;
    private final UserFamilyRepository userFamilyRepository;

    public PermissionApplicationService(
            UserRepositoryImpl userRepository,
            FamilyTreeRepositoryImpl familyTreeRepository,
            UserFamilyRepositoryImpl userFamilyRepository) {
        this.userRepository = userRepository;
        this.familyTreeRepository = familyTreeRepository;
        this.userFamilyRepository = userFamilyRepository;
    }

    /**
     * 检查当前用户是否为系统管理员
     * @return 是否为系统管理员
     */
    public boolean isSystemAdmin() {
        if (!StpUtil.isLogin()) {
            return false;
        }
        
        Long userId = StpUtil.getLoginIdAsLong();
        Optional<User> userOptional = userRepository.findById(userId);
        return userOptional.isPresent() && "ADMIN".equals(userOptional.get().getRole());
    }

    /**
     * 检查当前用户是否是特定家族树的创建者
     * @param familyTreeId 家族树ID
     * @return 是否为创建者
     */
    public boolean isFamilyTreeCreator(Long familyTreeId) {
        if (!StpUtil.isLogin()) {
            return false;
        }
        
        Long userId = StpUtil.getLoginIdAsLong();
        Optional<FamilyTree> familyTreeOptional = familyTreeRepository.findById(familyTreeId);
        return familyTreeOptional.isPresent() && userId.equals(familyTreeOptional.get().getCreatorId());
    }

    /**
     * 检查当前用户在特定家族树中的角色
     * @param familyTreeId 家族树ID
     * @return 用户在家族树中的角色
     */
    public String getUserRoleInFamilyTree(Long familyTreeId) {
        if (!StpUtil.isLogin()) {
            return null;
        }
        
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 如果是系统管理员，拥有所有权限
        if (isSystemAdmin()) {
            return "ADMIN";
        }
        
        // 检查是否是家族树创建者
        if (isFamilyTreeCreator(familyTreeId)) {
            return "ADMIN";
        }
        
        // 检查用户与家族树的关联关系
        Optional<UserFamily> userFamilyOptional = userFamilyRepository.findByUserIdAndFamilyTreeId(userId, familyTreeId);
        if (userFamilyOptional.isPresent()) {
            return userFamilyOptional.get().getRole();
        }
        
        // 默认为访客角色
        return "GUEST";
    }

    /**
     * 检查当前用户是否可以访问特定家族树
     * @param familyTreeId 家族树ID
     * @return 是否可以访问
     */
    public boolean canAccessFamilyTree(Long familyTreeId) {
        String role = getUserRoleInFamilyTree(familyTreeId);
        return role != null && !"GUEST".equals(role);
    }

    /**
     * 检查当前用户是否可以编辑特定家族树
     * @param familyTreeId 家族树ID
     * @return 是否可以编辑
     */
    public boolean canEditFamilyTree(Long familyTreeId) {
        String role = getUserRoleInFamilyTree(familyTreeId);
        return "ADMIN".equals(role) || "MEMBER".equals(role);
    }

    /**
     * 检查当前用户是否可以管理特定家族树（添加/删除成员等）
     * @param familyTreeId 家族树ID
     * @return 是否可以管理
     */
    public boolean canManageFamilyTree(Long familyTreeId) {
        String role = getUserRoleInFamilyTree(familyTreeId);
        return "ADMIN".equals(role);
    }
}